import React, { memo, useCallback } from "react";
import { connect, useDispatch } from "react-redux";
import classNames from "classnames";
import { CloseOutlined } from "@ant-design/icons";

import { WarpDiv } from "./style";
import { updateActiveFileId, removeOpenFile } from "../../redux/actions/files";

const TopTab = memo(function Index(props) {
  const { openIds, activeId, files } = props;
  const dispatch = useDispatch();

  //点击
  const handleClick = useCallback(
    (item) => {
      return () => {
        if (item === activeId) {
          //关闭当前，让前一个选中
          const index = openIds.indexOf(item);
          if (index >= 0) {
            dispatch(
              updateActiveFileId(openIds[index - 1 < 0 ? index + 1 : index - 1])
            );
          }
        }
        dispatch(removeOpenFile(item));
      };
    },
    [dispatch, activeId, openIds]
  );

  //切换tab
  const handleChangeTab = useCallback(
    (item) => {
      return () => {
        //触发更新activeFileId
        dispatch(updateActiveFileId(item));
      };
    },
    [dispatch]
  );

  return (
    <WarpDiv>
      {openIds.map((item) => {
        return (
          <div
            key={item}
            className={classNames("item", {
              "item-selected": item === activeId,
            })}
          >
            <span className="name" onClick={handleChangeTab(item)}>
              {files[item]?.name}
            </span>
            {item === activeId && <CloseOutlined onClick={handleClick(item)} />}
          </div>
        );
      })}
    </WarpDiv>
  );
});

export default connect((state) => ({
  activeId: state.files.activeFileId,
  openIds: state.files.openedFilesIdArr,
  files: state.files.filesObj,
}))(TopTab);
